package com.jeff.android.lab.jetpack.datastore

import android.os.Bundle
import android.widget.Button
import androidx.lifecycle.lifecycleScope
import butterknife.BindView
import com.jack.module.jetpack.UserInfo
import com.jeff.android.lab.BaseFragment
import com.jeff.android.lab.R

import com.jack.module.jetpack.datastore.preferences.DataStorePreferences
import com.jack.module.jetpack.datastore.proto.DataStoreProto
import com.jeff.utils.ToastUtil
import kotlinx.coroutines.launch

/**
 * @author: dingfeng
 * @date: 2020-10-29
 * @since: 1.0.0
 */
class DataStoreFragment : BaseFragment() {

    @BindView(R.id.btn_write)
    lateinit var btnWrite: Button

    @BindView(R.id.btn_read)
    lateinit var btnRead: Button

    override fun getRootLayout(): Int {
        return R.layout.jetpack_datastore_fragment
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DataStorePreferences.init(mContext)
        DataStoreProto.init(mContext)
    }

    override fun initView() {
        btnWrite.setOnClickListener {
            write()
        }
        btnRead.setOnClickListener {
            read()
        }
    }

    fun write() {
        lifecycleScope.launch {
            DataStorePreferences.write("name", "Jack")

            val user = UserInfo(0, "Jack.D", 30, "10086")

            DataStoreProto.saveUserInfo(user)
        }
    }

    fun read() {
        lifecycleScope.launch {
            val data = DataStorePreferences.readData("name")
            ToastUtil.show(mContext, data)

            val user = DataStoreProto.readUserInfo()
            ToastUtil.show(mContext, user.toString())
        }
    }

}
